import util from "../../utils/util";
import answerUtil from "../../utils/answerUtil";
Page({
  data: {
    colorArray: ['#0AFF00', '#EF0002', '#F3FF08'], // 绿1 红2 黄3
    currentColor: '',//当前显示颜色
    correctAnswer: '',//正确答案
    tabNum: null,//键盘默认选中效果
    answeredIndices: [],// 记录已经出现过的颜色索引
    currentIndex: 0, // 当前题目索引
    totalCount: 0, //题目总数
    count: 0, //记录做题次数
    isExercise: true, //是否是练习题
    countdownTime: 10, // 倒计时时间
    countdownInterval: null, // 存储 interval ID
    questionIndex: 0, //当前题型索引
    isShowTip: false, //练习结束提示
    questionStartTime: null,//记录题目开始时间
    answerRecords: [],//答题记录
    isClick: false, // 防止快速点击
  },
  onLoad() {
    this.getTopicData();
    this.showRandomColor();
     // 初始化时加载已有的答题记录
     const savedAnswerRecords = answerUtil.getAnswerRecords();
     this.setData({
       answerRecords: savedAnswerRecords
     });
  },
  // 获取题目信息
  getTopicData() {
    const questionIndex = wx.getStorageSync('questionInfo').questionNumber;
    const {count} = util.getData(questionIndex);
    this.setData({
      totalCount: count,
      questionIndex
    })
  },
  // 生成随机颜色(练习题)
  showRandomColor() {
    let { colorArray, answeredIndices } = this.data;
    if (answeredIndices.length >= 3) {
      this.setData({
        isExercise:false,
        isShowTip:true,
        answeredIndices:[]
      })
      return
    }
    let availableIndices = [0, 1, 2].filter(i => !answeredIndices.includes(i));
    let randomIndex = availableIndices[Math.floor(Math.random() * availableIndices.length)];
    this.setData({
      currentColor: colorArray[randomIndex],
      correctAnswer: (randomIndex + 1).toString(),
      tabNum: null,
      answeredIndices: [...answeredIndices, randomIndex]
    });
    this.startCountdown(); // 添加倒计时
  },
  // 生成随机颜色(正式题)
  showQuestion() {
    let { colorArray, answeredIndices} = this.data;
    const availableIndices = [0, 1, 2].filter(i => !answeredIndices.includes(i));
    const randomIndex = availableIndices[Math.floor(Math.random() * availableIndices.length)];
    this.setData({
      currentColor: colorArray[randomIndex],
      correctAnswer: (randomIndex + 1).toString(),
      tabNum: null,
      answeredIndices: [...answeredIndices, randomIndex],
      questionStartTime: new Date().getTime()//记录题目开始时间
    });
    this.startCountdown(); // 添加倒计时
  },
  // 启动倒计时
  startCountdown() {
    const { countdownInterval } = this.data;
    // 清除已有倒计时
    if (countdownInterval) {
      clearInterval(countdownInterval);
    }

    this.setData({ countdownTime: 10 });

    const interval = setInterval(() => {
      this.setData({
        countdownTime: this.data.countdownTime - 1
      });

      if (this.data.countdownTime <= 0) {
        this.handleTimeout(); // 处理超时逻辑
        clearInterval(interval);
      }
    }, 1000);

    this.setData({ countdownInterval: interval });
  },
  // 超时事件
  handleTimeout() {
    wx.showToast({
      title: '已超时',
      icon: 'none',
      duration: 1000
    });
    setTimeout(() => {
      let { isExercise } = this.data;
      if (isExercise) {
        this.showRandomColor();
      } else {
        // 使用共用方法创建并保存答题记录
        const newAnswerRecords = this.createAndSaveAnswerRecord(true);
        this.setData({
          answerRecords: newAnswerRecords
        })
        this.onNextQuestion()
      }
    }, 1000);
  },
  onTap(e) {
    if(this.data.isClick){
      return
    }
     // 设置处理状态
    this.setData({
      isClick: true
    }); 

    const { value } = e.currentTarget.dataset;
    const { correctAnswer, isExercise } = this.data;
    this.setData({ tabNum: value });
    let isCorrect;
    if (value === correctAnswer) {
      isCorrect = true
    } else {
      isCorrect = false
    }

    // 清除倒计时
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval);
      this.setData({ countdownInterval: null });
    }
    if (isExercise) {
      this.showRandomColor();
      this.setData({
        isClick: false
      });
    } else {
      // 使用共用方法创建并保存答题记录
      const newAnswerRecords = this.createAndSaveAnswerRecord(false, value,isCorrect);
      this.setData({
        answerRecords: newAnswerRecords
      })
      this.onNextQuestion()
    }
  },
  // 处理下一题
  onNextQuestion(){
    let { answeredIndices,count,totalCount} = this.data;
    if (answeredIndices.length >= 3) {
      let newCount = count + 1;
      this.setData({
        answeredIndices: [],
        count: newCount
      });
      if (newCount >= totalCount) {
        // 所有题目完成
        let questionNumber = this.data.questionIndex + 1;
        const prevInfo = wx.getStorageSync('questionInfo') || {};
        wx.setStorageSync('questionInfo', {
          ...prevInfo,
          questionNumber
        });
        util.navigateByDesc(questionNumber);
        this.setData({
          isClick: false
        });
        return;
      }
      this.showQuestion();
        this.setData({
          isClick: false
        });
      return;
    }
    this.showQuestion();
      this.setData({
        isClick: false
      });
  },
  // 开始测试
  onStar() {
    this.setData({
      isShowTip: false,
      answeredIndices: []
    })
    this.showQuestion();
  },
  // 处理答题记录
  createAndSaveAnswerRecord(isTimeout = false, userOption = '',isRight = false) {
    const {questionStartTime,questionIndex,correctAnswer} = this.data;
    const questionList = wx.getStorageSync('questionInfo').questionList;
    const currentTopic = questionList[questionIndex]
    // 计算答题时间
    const endTime = new Date().getTime();
    const answerTime = answerUtil.calculateAnswerTime(questionStartTime, endTime);

    // 判断是否正确（超时视为错误）
    let option = '';
    if (!isTimeout) {
      option = userOption;
      isRight = isRight ? 1 : 0;
    }
    
    // 创建答题记录
    const answerRecord = answerUtil.createAnswerRecord({
      qosId: 0,
      anserTime: answerTime,
      isRight: isRight,
      option: option,
      classify: currentTopic.typeCode,
      stem: '',
      accuracy: '',
      timeStemp: endTime.toString(),
      everyTxt: '',
      rightOption: correctAnswer,
      score: 0,
    });
    
    // 添加答题记录
    const newAnswerRecords = answerUtil.addAnswerRecord(answerRecord);
    
    return newAnswerRecords;
  },
  onUnload() {
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval);
      this.setData({ countdownInterval: null });
    }
    // 页面卸载时确保答题记录已保存
    answerUtil.saveAnswerRecords(this.data.answerRecords);
  }
});
